const fs = require('fs');
const gm = require('gm');
const path = require('path');
const exec = require('child_process').exec;

const async = require('async');

const scale_new = 0.5;

const dir_sources = 'C:/Users/chengguoqiang/Desktop/TestForCC/assets/';
const dir_out = 'C:/Users/chengguoqiang/Desktop/TestForCC/assets/';
// const dir_out = './outRes/';

// const dir_sources = 'D:/client/client_wbqj_fix_sync_final/assets/resources/gl_zh/';
// const dir_out = 'D:/client/client_wbqj_fix_sync_final/assets/resources/gl_zh/';


function loopFiles(dir, callback, type) {
    let stat = fs.statSync(dir);
    if (stat.isDirectory()) {
        let files = fs.readdirSync(dir);
        files.forEach(_f => {
            loopFiles(path.join(dir, _f), callback, type);
        })
    } else if (type.split('|').indexOf(path.extname(dir)) >= 0) {
        callback && callback(dir)
    }
}

// let files = fs.readdirSync(dir_sources);
// files.forEach(_f => {
//     if (path.extname(_f) == '.png')
//         scaleImg(path.join(dir_sources, _f), 50)
// })



// loopFiles(dir_sources, f => {
//     scaleImg(f, 0.6);
// }, '.png|.jpg');

let files = [];

loopFiles(dir_sources, f => {
    // console.log("f:", f);
    if (f.includes("spine")) return;
    files.push(f);
}, '.png|.jpg');

let total = files.length;
let cur = 0;
async.mapLimit(files, 50, (file, callback) => {
    scaleImg(file, scale_new, callback);
}, (err, result) => {
    if (err) {
        console.error("result error");
        console.error(err);
        return;
    }
    console.log('all done')
    fs.writeFileSync('./result.txt', JSON.stringify(result, null, 2))
})


function scaleImg(file, scale, callback) {
    let output = path.join(dir_out, path.relative(dir_sources, file));
    let _odir = path.dirname(output);
    if (!fs.existsSync()) {
        fs.mkdirSync(_odir, { recursive: true });
    }
    let stat = gm(file);
    stat.size((err, size) => {

        let scaledWidth = Math.round(size.width * scale)
        let scaledHeight = Math.round(size.height * scale)

        stat.resize(scaledWidth, scaledHeight).write(output, (err) => {
            if (err) {
                console.error('write error', err);
            } else {
                // console.log(`raw size: ${size.width}*${size.height} scaled: ${scaledWidth}*${scaledHeight}`);
                console.log(cur + '/' + total, ' write done', output)
            }
            compress(output, 1, callback);
        })
    })
}

//压缩 https://pngquant.org/
function compress(file, quality, callback) {
    let cmd = `.${path.sep}exec${path.sep}pngquant.exe --force --verbose 256 ${file} --output ${file}`;
    exec(cmd, function (err, stdout, stderr) {
        if (err) {
            console.error('compress error ' + file + ' | ' + err);
        } else {
            // console.log(`${cur}/${total} write file done & compress done`, file)
        }
        cur++;
        callback && callback(null, file);
    })

}